package com.client.job.core.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.client.job.core.annos.MJobAnnotation;
import com.client.job.core.annos.SectionRegister;
import com.client.job.core.model.MJob;
import com.client.job.core.model.MJobInstance;
import com.client.job.core.model.MJobVo;
import com.client.job.socket.ClientByNettyClient;
import com.client.job.utils.BeanReflectUtils;
import com.client.job.utils.DataResult;
import com.client.job.utils.IPUtils;
import com.client.job.utils.MJobUtils;

/**
 * 注册组件
 * @des
 * @author mengxiangzhong
 * @date 2021年9月10日
 *
 */

@Component
public class TaskRegisterCompent {
	

	@Value("${server.port:8080}")
	private String serverPort;

	@Value("${spring.application.name:no}")
	private String appName;

	@Value("${job.server.url}")
	private String jobServerUrl;

	@Value("${server.context-path:/}")
	private String baseUrl;

	private ClientByNettyClient client;


	/**
	 * 获取到服务信息
	 * @return
	 */
	public List<String> getServerInfo() {
		return  Arrays.asList(appName,serverPort);
	}
	
	@SuppressWarnings("static-access")
	public  void initSocketCollect(){
		if(client == null){
			client.initUrl(jobServerUrl, MJobUtils.genServerFlag(appName, serverPort));
			client.connectWebSocket();
		}
	}

	@SuppressWarnings("static-access")
	public void scanTasksAndSendTask() throws Exception {
		// 扫描出当前应用所有的任务
		Map<String, MJobAnnotation> map = SectionRegister.SECTION_MAP;
		
		List<MJobVo> voList = new ArrayList<>();
		for (Entry<String, MJobAnnotation> e : map.entrySet()) {
			voList.add(registerJob(e.getKey(), e.getValue()));
		}
		client.sengMessage(JSON.toJSONString(DataResult.buildSuccess(voList).buildRequestType(0)));
		
		
	}



	
	/**
	 * Job远程注册
	 * 
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	private MJobVo registerJob(String classLong, MJobAnnotation ma) throws Exception {
		// 组装任务
		MJob jd = new MJob();
		jd.setJobName(ma.jobName());
		jd.setJobCode(ma.jobCode());
		jd.setCron(ma.cron());
		jd.setKeyName(ma.keyName());
		jd.setZone(ma.zone());
		jd.setToLong(classLong);

		// 组装任务实例
		MJobInstance jm = MJobInstance.builder().port(serverPort).appName(appName).machineIp(IPUtils.getLocalInnetIp())
				.machineTime(new Date().getTime()).basePath(baseUrl).build();
		Map<String, Object> jdmap = BeanReflectUtils.beanProToListKv(jd);
		jdmap.putAll(BeanReflectUtils.beanProToListKv(jm));
		jdmap.remove("params");

		return MJobVo.builder().mJob(jd).mJobInstanceList(Arrays.asList(jm)).build();
	}

}
